package com.sky.service.user.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.exception.DataException;
import com.sky.exception.NoCourierException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.common.AddressBookMapper;
import com.sky.mapper.common.OrderDetailMapper;
import com.sky.mapper.common.OrderMapper;
import com.sky.mapper.common.ShoppingCartMapper;
import com.sky.pojo.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.user.OrderDispatchService;
import com.sky.service.user.OrderService;
import com.sky.service.user.WxPayService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.vo.OrdersVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true)
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private OrderDispatchService orderDispatchService;
    /**
     * 下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
//        1.校验参数是否合法 如不合法则抛异常
        if(null == ordersSubmitDTO || null == ordersSubmitDTO.getAddressBookId()){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        //1.1 判断购物车中是否有数据 如果没有数据则报错
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.listByUserId(userId);
        if(null == shoppingCarts || shoppingCarts.size() == 0){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

//        2.如果传递的是dto 则创建pojo并拷贝数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
//        3.补齐不能拷贝的数据(创建时间 用户id等)
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(UUID.randomUUID().toString().replaceAll("-",""));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());
        //预计送达时间
        order.setDeliveryTime(LocalDateTime.now());
        // 4.调用mapper插入数据
        orderMapper.insert(order);


        //5. 构建一个订单详情列表
        List<OrderDetail> details = new ArrayList<>(shoppingCarts.size());
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(order.getId());
            details.add(orderDetail);
        }
        //6. 批量添加订单详情数据
        orderDetailMapper.batchInert(details);

        //7. 清空购物车数据
        shoppingCartMapper.clean(userId);

        OrderSubmitVO vo = OrderSubmitVO.builder()
                .id(order.getId())
                .orderAmount(order.getAmount())
                .orderNumber(order.getNumber())
                .orderTime(order.getOrderTime())
                .build();

        return vo;
    }

    /**
     * 根据条件分页查询订单的数据
     *
     * @param queryDTO
     * @return
     */
    @Override
    public Result<PageResult<OrdersVO>> pageQuery(OrdersPageQueryDTO queryDTO) {
        //1. 校验参数
        if(null == queryDTO){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        if(queryDTO.getPage() <=0){
            queryDTO.setPage(1);
        }

        if(queryDTO.getPageSize() <= 0){
            queryDTO.setPageSize(10);
        }

        //2. 调用PageHelper设置分页参数
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());

        //3. 调用mapper查询分页数据
        Page<OrdersVO> voPage = orderMapper.pageQuery(queryDTO);

        //4. 封装返回结果并返回
        PageResult<OrdersVO> pageResult = new PageResult<OrdersVO>();
        pageResult.setTotal(voPage.getTotal());
        pageResult.setRecords(voPage.getResult());

        return Result.success(pageResult);
    }

    /**
     * 统计各个状态的订单数量
     *
     * @return
     */
    @Override
    public Result<OrderStatisticsVO> statistics() {
       // OrderStatisticsVO orderStatisticsVO = statistics1(); 传统的实现 效率较低
//        OrderStatisticsVO orderStatisticsVO = statistics2(); // 多线程的方式实现 主要应用于数据量比较大或者有海量数据需要处理的场景
        //OrderStatisticsVO orderStatisticsVO = statistics3(); //通过一条sql分组统计实现各个状态的订单统计 主要适用的场景是数据量不大(中等数据库)
        OrderStatisticsVO orderStatisticsVO = orderMapper.groupByStatus1(); //行转列的方式实现 主要适用的场景是数据量不大(中等数据库)

        return Result.success(orderStatisticsVO);
    }

    @Override
    public Result<OrdersVO> getDetailById(Long orderId) {
        OrdersVO vo = orderMapper.getDetailById(orderId);
        return Result.success(vo);
    }

    /**
     * 商家取消订单
     *
     * @param cancelDTO
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public Result<String> cancelOrder(OrdersCancelDTO cancelDTO) throws IOException {
        //1. 校验参数是否合法
        if(null == cancelDTO || null == cancelDTO.getId()){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        Orders orders = orderMapper.selectById(cancelDTO.getId());
        if(null == orders || orders.getStatus()==1||orders.getStatus()==6||orders.getStatus()==7||orders.getStatus()==8){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        //2. 调用微信的退款接口进行退款 退款申请受理成功以后在更新订单的状态
        wxPayService.refunds(orders, cancelDTO.getCancelReason());
        //3. 返回结果

        return Result.success();
    }

    private OrderStatisticsVO statistics3(){
        List<Map> list = orderMapper.groupByStatus();

        Integer waiting4MerchantReceiveOrders = 0;
        Integer waitng4RiderReceiveOrders = 0;
        Integer toBeDeliveryOnProgressOrders = 0;
        Integer toBeArrivedOrders = 0;
        Integer completedOrders = 0;
        Integer canceledOrders = 0;
        if(null != list && list.size() > 0){
            for (Map map : list) {
                int status =Integer.parseInt(map.get("status").toString()) ;
                int total = Integer.parseInt(map.get("total").toString());
                switch (status){
                    case 2:
                        waiting4MerchantReceiveOrders=total;
                        break;
                    case 3:
                        waitng4RiderReceiveOrders=total;
                        break;
                    case 4:
                        toBeDeliveryOnProgressOrders=total;
                        break;
                    case 5:
                        toBeArrivedOrders=total;
                        break;
                    case 6:
                        completedOrders=total;
                        break;
                    case 7:
                        canceledOrders=total;
                        break;
                }
            }
        }

        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .waiting4MerchantReceiveOrders(waiting4MerchantReceiveOrders)//  status = 2  等待商家接单
                .waitng4RiderReceiveOrders(waitng4RiderReceiveOrders)//  status = 3  等待骑手接单
                .toBeDeliveryOnProgressOrders(toBeDeliveryOnProgressOrders)//  status = 4  待出货订单数
                .toBeArrivedOrders(toBeArrivedOrders)//  status = 5  待送达订单数
                .completedOrders(completedOrders) // status = 6  已完成订单数
                .canceledOrders(canceledOrders)//  status = 7  已取消订单数
                .build();

        return orderStatisticsVO;
    }

    private OrderStatisticsVO statistics2(){
        Future<Integer> future1 = threadPoolExecutor.submit(() -> orderMapper.countStatus(Orders.TO_BE_CONFIRMED));
        Future<Integer> future2 = threadPoolExecutor.submit(() -> orderMapper.countStatus(Orders.CONFIRMED));
        Future<Integer> future3 = threadPoolExecutor.submit(() -> orderMapper.countStatus(Orders.TOBEDELIVERED));
        Future<Integer> future4 = threadPoolExecutor.submit(() -> orderMapper.countStatus(Orders.TOBEDELIVERED));
        Future<Integer> future5 = threadPoolExecutor.submit(() -> orderMapper.countStatus(Orders.COMPLETE_ORDER));
        Future<Integer> future6 = threadPoolExecutor.submit(() -> orderMapper.countStatus(Orders.CANCELLED_ORDER));

        try {
            Integer waiting4MerchantReceiveOrders = future1.get();
            Integer waitng4RiderReceiveOrders = future2.get();
            Integer toBeDeliveryOnProgressOrders = future3.get();
            Integer toBeArrivedOrders = future4.get();
            Integer completedOrders = future5.get();
            Integer canceledOrders = future6.get();

            OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                    .waiting4MerchantReceiveOrders(waiting4MerchantReceiveOrders)//  status = 2  等待商家接单
                    .waitng4RiderReceiveOrders(waitng4RiderReceiveOrders)//  status = 3  等待骑手接单
                    .toBeDeliveryOnProgressOrders(toBeDeliveryOnProgressOrders)//  status = 4  待出货订单数
                    .toBeArrivedOrders(toBeArrivedOrders)//  status = 5  待送达订单数
                    .completedOrders(completedOrders) // status = 6  已完成订单数
                    .canceledOrders(canceledOrders)//  status = 7  已取消订单数
                    .build();

            return orderStatisticsVO;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    private OrderStatisticsVO statistics1(){
        Integer waiting4MerchantReceiveOrders = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer waitng4RiderReceiveOrders = orderMapper.countStatus(Orders.CONFIRMED);
        Integer toBeDeliveryOnProgressOrders = orderMapper.countStatus(Orders.TOBEDELIVERED);
        Integer toBeArrivedOrders = orderMapper.countStatus(Orders.TOBEDELIVERED);
        Integer completedOrders = orderMapper.countStatus(Orders.COMPLETE_ORDER);
        Integer canceledOrders = orderMapper.countStatus(Orders.CANCELLED_ORDER);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .waiting4MerchantReceiveOrders(waiting4MerchantReceiveOrders)//  status = 2  等待商家接单
                .waitng4RiderReceiveOrders(waitng4RiderReceiveOrders)//  status = 3  等待骑手接单
                .toBeDeliveryOnProgressOrders(toBeDeliveryOnProgressOrders)//  status = 4  待出货订单数
                .toBeArrivedOrders(toBeArrivedOrders)//  status = 5  待送达订单数
                .completedOrders(completedOrders) // status = 6  已完成订单数
                .canceledOrders(canceledOrders)//  status = 7  已取消订单数
                .build();
        return orderStatisticsVO;
    }

    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        //校验并修正数据
        if(pageNum <= 0){
            pageNum = 1;
        }

        if(pageSize <= 10){
            pageSize = 10;
        }

        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageOrderQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList(page.getResult().size()); // 以后凡是我们使用集合 都需要尽量给集合长度 如果不给长度可能会导致集合多次扩容影响效率

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 用户取消订单
     *
     * @param id
     */
    public void userCancelById(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.selectById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            wxPayService.refunds(ordersDB, "用户取消");
        }else{
            // 更新订单状态、取消原因、取消时间 - 更新的是用户未付款的订单
            orders.setStatus(Orders.CANCELLED_ORDER);
            orders.setCancelReason("用户取消");
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.updateById(orders);
        }
    }

    /**
     * 再来一单
     *
     * @param id
     */
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 商家接单
     *
     * @param confirmDTO
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public Result<Courier> confirm(OrdersConfirmDTO confirmDTO) {
        //1. 参数校验 不合法抛出异常
        if(null == confirmDTO || null == confirmDTO.getId()){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        //2. 查询订单
        Orders orders = orderMapper.selectById(confirmDTO.getId());

        //3. 判断订单是否存在 如果不在在抛出异常
        if(null == orders){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        //4. 通过订单选择一个选择一个骑手接单
        Courier courier = orderDispatchService.dispatchCourier(orders, null, null);

        //5.判断是否找到了骑手 如果没有找到 则循环三次继续查找
        if(null == courier){
            for (int i =0; i < 3; i++){
                try {
                    TimeUnit.SECONDS.sleep(30);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                courier = orderDispatchService.dispatchCourier(orders, null, null);
                if(null != courier) break;
            }
        }

        //6. 循环结束以后在判断是否找到了骑手 如果没有找到则抛出异常
        if(null == courier){
            throw new NoCourierException("暂时找不到骑手，请稍后再试");
        }

        //7. 更新订单的状态
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.updateById(orders);

        return Result.success(courier);
    }
}
